package com.gugee.ins.data.analysis.service.impl;

import cn.hutool.core.date.DateUtil;
import com.gugee.common.thread.ScheduleTemplate;
import com.gugee.ins.common.constant.AiConst;
import com.gugee.ins.common.constant.FaceRecognitionCodeEnum;
import com.gugee.ins.common.constant.InsBloggerMsgTypeCodeEnum;
import com.gugee.ins.common.dal.ai.AiAnalysisClient;
import com.gugee.ins.common.dal.service.blogger.InsBloggerDao;
import com.gugee.ins.common.dal.service.blogger.InsBloggerMainDao;
import com.gugee.ins.common.model.ai.FaceRecognition;
import com.gugee.ins.data.analysis.config.InsAnalysisConfig;
import com.gugee.ins.data.analysis.service.InsAnalysisAvatarService;
import com.gugee.ins.data.common.msg.InsBloggerMessage;
import com.xiguaji.boot.toolkit.ThreadPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

/**
 * insBloggerLocation 服务
 * @author Huangxin
 */
@Slf4j
@Service
public class InsAnalysisAvatarServiceImpl implements InsAnalysisAvatarService {

    /**
     * 配置
     */
    @Autowired
    InsAnalysisConfig insAnalysisConfig;

    /**
     * 线程调度
     */
    @Autowired
    ScheduleTemplate scheduleTemplate;

    /**
     * ai
     */
    @Autowired
    AiAnalysisClient aiAnalysisClient;

    /**
     * InsBloggerDao
     */
    @Autowired
    InsBloggerDao insBloggerDao;

    /**
     * InsBloggerDao
     */
    @Autowired
    InsBloggerMainDao insBloggerMainDao;

    /**
     * kafkaTemplate
     */
    @Autowired
    KafkaTemplate<Long,InsBloggerMessage> kafkaTemplateInsAnalysisAvatar;

    /**
     * 线程池
     */
    ForkJoinPool forkJoinPool;

    /**
     * 线程名
     */
    private String workName = "insAnalysisAvatar-worker";

    /**
     * 初始化线程池
     */
    @PostConstruct
    public void init() {
        forkJoinPool = ThreadPoolUtils.forkJoinPool(insAnalysisConfig.getInsAnalysisAvatarCorePollSize(), workName);
        scheduleTemplate.attach(workName, forkJoinPool);
    }

    /**
     * 处理 分析头像 任务
     * @param insBloggerMessages
     */
    @Override
    public void handleAnalysisAvatar(List<InsBloggerMessage> insBloggerMessages) {
        try {
            forkJoinPool.submit(() -> insBloggerMessages.parallelStream().forEach(msg -> {
                try {
                    // 分析头像
                    analysisAvatar(msg);
                } catch (Exception ex) {
                    log.error("insAnalysisAvatar error. uid:{}, error :{}" ,
                            msg.getUid(),ex.getMessage());
                }
            })).get();
        } catch (Exception ex) {
            log.error("insAnalysisAvatar thread error.  {}" ,  ex.getMessage());
        }
    }

    /**
     * 分析头像
     *
     * @param insBloggerMessage
     */
    public void analysisAvatar(InsBloggerMessage insBloggerMessage){
        long start = System.currentTimeMillis();
        long uid = insBloggerMessage.getUid();
        String url = insBloggerMessage.getPicUrl();

        // 判断是否需要处理
        if(insBloggerMessage.getTypeCode() != InsBloggerMsgTypeCodeEnum.NO_HANDLE_AND_DO_OTHER_OPT.getCode()){
            // 查询博主帖子，将帖子的title内容（文字长度在一定范围的）发送给ai接口分析语言
            try{
                analysisAvatar(uid,url);
            }catch (Exception e){
                log.error(" insMainBlogger insAnalysisAvatar error. uid:{}, error :{}",uid,e.getMessage());
            }
        }
        long limitTime = start / 1000 - insAnalysisConfig.getInsAnalysisAvatarIntervalDay() * 24 * 3600;
        // 查询他的活跃粉丝且发送
        List<InsBloggerMessage> subMessages = insBloggerMainDao.findInsAnalysisAvatarMessageByUid(uid,limitTime);
        if(subMessages != null && !subMessages.isEmpty()){
            try {
                forkJoinPool.submit(() -> subMessages.parallelStream().forEach(msg -> {
                    try {
                        // 分析头像
                        analysisAvatar(msg.getUid(),msg.getPicUrl());
                    } catch (Exception ex) {
                        log.error("insBlogger insAnalysisAvatar error. uid:{}, error :{}",msg.getUid(),ex.getMessage());
                    }
                })).get();
            } catch (Exception e) {
                log.error("insBlogger insAnalysisAvatar thread error. error :{}",e.getMessage());
            }

            // 发送优先统计的消息
            sendPriorityStMsg(insBloggerMessage);
        }

        if ((System.currentTimeMillis() - start) / 1000 > insAnalysisConfig.getInsAnalysisAvatarDebugTimeLimit()) {
            log.info("insAnalysisAvatar uid:{} use time:{}s", uid,(System.currentTimeMillis() - start) / 1000);
        }
    }

    /**
     * 分析头像
     * @param uid
     * @param url
     */
    public void analysisAvatar(long uid, String url){
        //调用ai接口
        try{
            FaceRecognition faceRecognition = aiAnalysisClient.getFaceRecognitionByPicUrl(uid,url);
            //处理结果枚举(0：成功，1002：图片下载问题，1003：程序异常， 18：qps上限 222202：图片无人脸)
            if(FaceRecognitionCodeEnum.SUCCESS.getCode() == faceRecognition.getErrorCode()
                    || FaceRecognitionCodeEnum.PIC_NO_FACE.getCode() == faceRecognition.getErrorCode()){
                int age = faceRecognition.getAge() <= AiConst.NOT_ANALYZED ? AiConst.UNKNOWN : faceRecognition.getAge();
                int gender;
                if(faceRecognition.getGender() == AiConst.FACE_RECOGNITION_MALE){
                    gender = AiConst.MALE;
                } else {
                    gender = faceRecognition.getGender() == AiConst.FACE_RECOGNITION_FEMALE ? AiConst.FEMALE : AiConst.UNKNOWN;
                }
                int birth = DateUtil.thisYear() - age;

                //更新数据库 blogger
                saveAnalysisAvatar(uid,age,gender,birth,faceRecognition.getRace());
            }else {
                log.error("调用ai人脸识别接口获取性别、年龄接口返回结果 error ,uid:{},errorCode:{},errorMsg:{}",
                        uid,faceRecognition.getErrorCode(),faceRecognition.getErrorCode());
                int gender;
                if(FaceRecognitionCodeEnum.QPS_FULL.getCode() == faceRecognition.getErrorCode()){
                    gender = AiConst.QPS_FULL;
                } else{
                    gender = FaceRecognitionCodeEnum.PIC_DOWNLOAD_ERROR.getCode() == faceRecognition.getErrorCode()
                            ? AiConst.PIC_NO_FACE : AiConst.IMPL_ERROR;
                }
                //更新数据库 blogger
                saveAnalysisAvatar(uid,AiConst.NOT_ANALYZED,gender,0,faceRecognition.getRace());
            }
        }catch (Exception e){
            log.error("insAnalysisAvatar 调用ai人脸识别接口获取性别、年龄接口过程 error ,uid:{},url:{},msg:{}",uid,url,e.getMessage());
        }
    }

    /**
     * 保存数据库
     * @param uid
     * @param age
     * @param gender
     * @param birth
     * @param race
     */
    public void saveAnalysisAvatar(long uid,int age,int gender,int birth,String race){
        //更新数据库 blogger
        insBloggerDao.updateAiGenderAndAiAgeByUid(age,gender,birth,race,uid);
        //更新数据库 blogger_main
        insBloggerMainDao.updateAiGenderAndAiAgeByUid(age,gender,birth,race,uid);
    }

    /**
     * 发送优先统计性别、年龄、种族的消息
     * @param insBloggerMessage
     */
    public void sendPriorityStMsg(InsBloggerMessage insBloggerMessage){
        insBloggerMessage.setTypeCode(InsBloggerMsgTypeCodeEnum.ST_GENERATION_RACE_GENDER.getCode());
        insBloggerMessage.setRetryTimes(insAnalysisConfig.getInsMBloggerActiveFollowerDataStPriorityRetryTimes());
        insBloggerMessage.setRetryLimitTimes(insAnalysisConfig.getInsMBloggerActiveFollowerDataStPriorityRetryTimes());
        insBloggerMessage.setEventTime(System.currentTimeMillis());
        kafkaTemplateInsAnalysisAvatar.send(insAnalysisConfig.getInsMBloggerActiveFollowerDataStPriorityTopic(),insBloggerMessage);
    }
}
